package com.gzhryc.net_marketing.cloud.account.delay;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.event.AbsDelayHandler;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.cloud.account.dao.db.TransferMoneyOrder;
import com.gzhryc.net_marketing.cloud.account.services.TransferMoneyOrderService;
import com.gzhryc.pay.adaptation.weixin.DefaultWXPayConfig;
import com.gzhryc.pay.adaptation.weixin.WXPayTransferMoneyService;
import com.gzhryc.pay.adaptation.weixin.msg.transfer.WXPayTransferMoneyPayResponse;
import com.gzhryc.shared_device.common.payment.dao.db.WXPayConfig;
import com.gzhryc.shared_device.common.payment.services.WXPayConfigService;

public class TransferMoneyDelayHandler extends AbsDelayHandler<TransferMoneyDelayEvent> {

    static Logger log = Logger.getLogger(TransferMoneyDelayHandler.class);

    @Override
    public boolean execute(TransferMoneyDelayEvent transferMoneyDelayEvent) {
        TransferMoneyOrder order = transferMoneyDelayEvent.getOrder();
        boolean isSuccess = false;
        try {
            if(TransferMoneyOrderService.self().waitToProcessing(order.getTradeNo())) {
                //触发转账
                WXPayConfig wxPayConfig = WXPayConfigService.self().getByAppId(order.getAppId());
                if (wxPayConfig != null) {
                    DefaultWXPayConfig defaultWXPayConfig = ClassTools.copy(new DefaultWXPayConfig(),wxPayConfig);
                    WXPayTransferMoneyService transferMoneyService = new WXPayTransferMoneyService(defaultWXPayConfig);
                    WXPayTransferMoneyPayResponse externalResult = transferMoneyService.applyTransferMoney(order);
                    if(externalResult != null){
                        TransferMoneyOrderService.self().updateExternalInfo(order.getTradeNo()
                                ,externalResult.getBatch_id(), JsonTools.toJson(externalResult),wxPayConfig.getMchId());
                        isSuccess = true;
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage(),e);
        }finally {
            if(!isSuccess){
                TransferMoneyOrderService.self().processingToWait(order.getTradeNo());
            }
        }
        return true;
    }
}
